import { Component, ViewChild, ElementRef } from '@angular/core';

import { NavController, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { TabsPage } from '../tabs/tabs'

import { LoginService, UserService } from './login.service';
import { NetworkConfig, LoginResponse } from '../../app/app.service';

@Component({
    selector: 'login-page',
    templateUrl: 'login.html'
})
export class LoginPage {

    @ViewChild('autoSignInput') autoSignInput: ElementRef;

    user: any;
    toast: any;

    constructor(public navCtrl: NavController, private loginService: LoginService, private userService: UserService, public toastCtrl: ToastController, public storage: Storage, public loadingCtrl: LoadingController) {
        this.user = {
            'userName': '',
            'passWord': ''
        };

    }

    ionViewDidLoad() {
        this.storage.get('autoSign').then((autoSign) => {
            this.autoSignInput.nativeElement.checked = autoSign;
            if (autoSign) {
                this.userService.getUser().then((user: any) => {
                    if (user !== null) {
                        console.log(this.navCtrl);
                        NetworkConfig.headers.DF_KEY = user.token;
                        this.navCtrl.push(TabsPage);
                    }
                });
            }
        });
    }

    login(e): void {
        console.log(e);
        let loader = this.loadingCtrl.create({
            content: "登录中,请稍候...",
            duration: 0
        });
        loader.present();
        this.loginService.login({ 'username': this.user.userName, 'password': this.user.passWord })
            .then((res: LoginResponse) => {
                loader.dismiss();
                if (res.code === 'SUCCESS') {
                    this.userService.setUser(res.data);
                    this.navCtrl.push(TabsPage);
                } else {
                    this.toast = this.toastCtrl.create({
                        message: res.userMsg,
                        duration: 1000
                    });
                    this.toast.present();
                }

            })
            .catch(function (err) {
                console.log(err);
            });
    }

    remenberTapped(e): void {
        if (e.srcElement.checked) {
            this.storage.set('autoSign', true);
        } else {
            this.storage.set('autoSign', true);
        }
    }

}
